package com.ztorn.fiscale.service.impl;

import java.math.BigDecimal;
import java.util.List;
import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ztorn.fiscale.mapper.FiscaleRefundBatchMapper;
import com.ztorn.fiscale.mapper.FiscaleRefundBatchDetailMapper;
import com.ztorn.fiscale.mapper.FiscaleRefundMatchingMapper;
import com.ztorn.fiscale.domain.FiscaleRefundBatch;
import com.ztorn.fiscale.domain.FiscaleRefundBatchDetail;
import com.ztorn.fiscale.domain.FiscaleRefundMatching;
import com.ztorn.fiscale.service.IFiscaleRefundBatchService;

/**
 * 退税申报批次Service业务层处理
 * 
 * @author ztorn
 * @date 2025-09-20
 */
@Service
public class FiscaleRefundBatchServiceImpl implements IFiscaleRefundBatchService 
{
    @Autowired
    private FiscaleRefundBatchMapper fiscaleRefundBatchMapper;
    
    @Autowired
    private FiscaleRefundBatchDetailMapper fiscaleRefundBatchDetailMapper;
    
    @Autowired
    private FiscaleRefundMatchingMapper fiscaleRefundMatchingMapper;

    /**
     * 查询退税申报批次
     * 
     * @param batchId 退税申报批次ID
     * @return 退税申报批次
     */
    @Override
    public FiscaleRefundBatch selectFiscaleRefundBatchById(Long batchId)
    {
        return fiscaleRefundBatchMapper.selectFiscaleRefundBatchById(batchId);
    }

    /**
     * 查询退税申报批次列表
     * 
     * @param fiscaleRefundBatch 退税申报批次
     * @return 退税申报批次
     */
    @Override
    public List<FiscaleRefundBatch> selectFiscaleRefundBatchList(FiscaleRefundBatch fiscaleRefundBatch)
    {
        return fiscaleRefundBatchMapper.selectFiscaleRefundBatchList(fiscaleRefundBatch);
    }

    /**
     * 新增退税申报批次
     * 
     * @param fiscaleRefundBatch 退税申报批次
     * @return 结果
     */
    @Override
    public int insertFiscaleRefundBatch(FiscaleRefundBatch fiscaleRefundBatch)
    {
        return fiscaleRefundBatchMapper.insertFiscaleRefundBatch(fiscaleRefundBatch);
    }

    /**
     * 修改退税申报批次
     * 
     * @param fiscaleRefundBatch 退税申报批次
     * @return 结果
     */
    @Override
    public int updateFiscaleRefundBatch(FiscaleRefundBatch fiscaleRefundBatch)
    {
        return fiscaleRefundBatchMapper.updateFiscaleRefundBatch(fiscaleRefundBatch);
    }

    /**
     * 批量删除退税申报批次
     * 
     * @param batchIds 需要删除的退税申报批次ID
     * @return 结果
     */
    @Override
    public int deleteFiscaleRefundBatchByIds(Long[] batchIds)
    {
        return fiscaleRefundBatchMapper.deleteFiscaleRefundBatchByIds(batchIds);
    }

    /**
     * 删除退税申报批次信息
     * 
     * @param batchId 退税申报批次ID
     * @return 结果
     */
    @Override
    public int deleteFiscaleRefundBatchById(Long batchId)
    {
        return fiscaleRefundBatchMapper.deleteFiscaleRefundBatchById(batchId);
    }
    
    /**
     * 生成退税数据
     * 
     * @param matchingIds 配单ID数组
     * @return 结果
     */
    @Override
    public FiscaleRefundBatch generateRefundData(Long[] matchingIds)
    {
        if (matchingIds == null || matchingIds.length == 0) {
            return null;
        }
        
        // 创建退税申报批次
        FiscaleRefundBatch batch = new FiscaleRefundBatch();
        String batchNo = "REFUND-" + System.currentTimeMillis() + "-" + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
        batch.setBatchNo(batchNo);
        batch.setDeclarationCount(matchingIds.length);
        batch.setStatus("pending");
        batch.setCreateTime(new Date());
        
        // 计算总退税金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        List<FiscaleRefundBatchDetail> details = new ArrayList<>();
        
        for (Long matchingId : matchingIds) {
            FiscaleRefundMatching matching = fiscaleRefundMatchingMapper.selectFiscaleRefundMatchingById(matchingId);
            if (matching != null) {
                // 这里应该根据报关单和发票信息计算退税金额
                // 简化处理，假设退税金额为发票金额的13%
                BigDecimal refundAmount = matching.getInvoice().getTotalAmount().multiply(new BigDecimal("0.13"));
                totalAmount = totalAmount.add(refundAmount);
                
                // 创建明细记录
                FiscaleRefundBatchDetail detail = new FiscaleRefundBatchDetail();
                detail.setBatchId(batch.getBatchId()); // 注意：这里需要在插入后才能获取到batchId
                detail.setMatchingId(matchingId);
                detail.setDeclarationId(matching.getDeclarationId());
                detail.setInvoiceId(matching.getInvoiceId());
                detail.setRefundAmount(refundAmount);
                detail.setStatus("pending");
                detail.setCreateTime(new Date());
                details.add(detail);
            }
        }
        
        batch.setTotalAmount(totalAmount);
        
        // 保存批次信息
        fiscaleRefundBatchMapper.insertFiscaleRefundBatch(batch);
        
        // 保存明细信息
        for (FiscaleRefundBatchDetail detail : details) {
            detail.setBatchId(batch.getBatchId()); // 设置正确的batchId
            fiscaleRefundBatchDetailMapper.insertFiscaleRefundBatchDetail(detail);
        }
        
        return batch;
    }
    
    /**
     * 正式申报
     * 
     * @param batchId 批次ID
     * @return 结果
     */
    @Override
    public int submitRefundDeclaration(Long batchId)
    {
        FiscaleRefundBatch batch = fiscaleRefundBatchMapper.selectFiscaleRefundBatchById(batchId);
        if (batch == null) {
            return 0;
        }
        
        // 更新批次状态为申报中
        batch.setStatus("submitting");
        batch.setSubmitTime(new Date());
        return fiscaleRefundBatchMapper.updateFiscaleRefundBatch(batch);
    }
    
    /**
     * 刷新申报状态
     * 
     * @param batchId 批次ID
     * @return 结果
     */
    @Override
    public int refreshRefundStatus(Long batchId)
    {
        FiscaleRefundBatch batch = fiscaleRefundBatchMapper.selectFiscaleRefundBatchById(batchId);
        if (batch == null) {
            return 0;
        }
        
        // 模拟状态刷新逻辑
        // 实际实现中应该调用税务局API获取最新状态
        String currentStatus = batch.getStatus();
        if ("submitting".equals(currentStatus)) {
            batch.setStatus("processing");
        } else if ("processing".equals(currentStatus)) {
            batch.setStatus("approved");
        } else if ("approved".equals(currentStatus)) {
            batch.setStatus("refunding");
        } else if ("refunding".equals(currentStatus)) {
            batch.setStatus("completed");
            batch.setCompleteTime(new Date());
        }
        
        return fiscaleRefundBatchMapper.updateFiscaleRefundBatch(batch);
    }
}